import moviepy.editor as mp
from flask import Flask, request, jsonify, render_template, send_from_directory
from PIL import Image
from werkzeug.utils import secure_filename
import os,datetime
import threading  # 引入多线程库
import time
import json
import tempfile
import datetime
import lunarcalendar  # 引入农历库
import random

# 设置临时目录路径
temp_dir = os.path.join(os.getcwd(), 'temp')
if not os.path.exists(temp_dir):
    os.makedirs(temp_dir)

os.environ['TMPDIR'] = temp_dir
    
app = Flask(__name__, static_url_path='/uploads', static_folder='uploads',template_folder='/p')

app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['UNZIPPED_FOLDER'] = 'unz'

# 密码
# 从本地的pwd.txt中读取密码
with open('hidden/pwd.txt', 'r') as f:
    ACCESS_PASSWORD = f.read().strip()

UPLOAD_FOLDER = 'uploads'
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)

UNZ = 'unz'
if not os.path.exists(UNZ):
    os.makedirs(UNZ)

# Dictionary to store comments with image index as key
image_comments = {}

ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif','JPG','mp4','MP4'}

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

# 允许从根目录访问文件
@app.route('/<path:filename>')
def serve_root_directory(filename):
    return send_from_directory('.', filename)  # 使用'.'代表根目录

@app.route('/')
def index():
    with open('index.html', 'rb') as f:
        return f.read()
    
@app.route('/winter/<path:filename>')
def serve_winter_image(filename):
    return send_from_directory('winter', filename)

@app.route('/hidden/<path:filename>')
def restricted_hidden_access(filename):
    if request.referrer is None or 'c15' not in request.referrer:  # 检查是否通过 /c15 路由跳转
        return "Access Forbidden: Unauthorized access.", 403
    return send_from_directory('hidden', filename)

@app.route('/15/<path:filename>')
def restricted_hidden_access2(filename):
    if request.referrer is None or 'c15' not in request.referrer:  # 检查是否通过 /c15 路由跳转
        return "Access Forbidden: Unauthorized access.", 403
    return send_from_directory('15', filename)


@app.route('/g')
def g():
    with open('gallery.html', 'rb') as f:
        return f.read()  # Use render_template to serve the gallery



@app.route('/c15', methods=['GET', 'POST'])
def c15():
    if request.method == 'POST':
        # 获取用户提交的密码
        password = request.form.get('password')
        if password == ACCESS_PASSWORD:
            # 如果密码正确，返回页面内容
            with open('hidden/15.html', 'rb') as f:
                return f.read()
        else:
            # 如果密码错误，返回错误提示
            return '''
                <p>密码错误，请重试。</p>
                <a href="/c15">返回</a>
            ''', 401

    # 显示密码输入表单
    return '''
        <!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录</title>
    <style>
        html, body {
            height: 100%;
            margin: 0;
            padding: 0;
            overflow-x: hidden;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
        }

        body {
            background-image: url("background.png");
            background-size: cover;
            background-position-x: center;
            background-repeat: no-repeat;
            height: 100vh;
            width: 100vw;
        }

        nav {
            background-color: #468ef3;
            padding: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-radius: 10px;
            width: 90%;
            margin: 20px auto;
        }

        nav a {
            color: white;
            text-decoration: none;
            padding: 10px 20px;
        }

        nav a:hover {
            background-color: #669fee;
            border-radius: 5px;
        }

        .login-container {
            background-color: #ffffffc3;
            border-radius: 5px;
            padding: 20px;
            width: 90%;
            max-width: 400px;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .login-container input[type="text"],
        .login-container input[type="password"] {
            width: 100%;
            padding: 10px;
            margin: 10px 0;
            border-radius: 5px;
            border: 1px solid #ccc;
        }

        .login-container button {
            width: 100%;
            padding: 10px;
            background-color: #468ef3;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }

        .login-container button:hover {
            background-color: #669fee;
        }

        footer {
            background-color: #468ef3;
            color: white;
            text-align: center;
            padding: 10px 0;
            margin-top: auto;
            width: 100%;
        }

        footer img {
            display: block;
            margin: 0 auto;
            max-width: 60%;
            max-height: 100px;
        }

        .footer-text {
            font-size: smaller;
            line-height: 2;
            color: #bdd2f0;
        }

        .footer-text a {
            line-height: 2;
            color: #bdd2f0;
        }
    </style>
</head>
<body>
    <nav>
        <a href="/">首页</a>
        <a href="/c15">政治</a>
        <a href="/g">画廊</a>
    </nav>

    <div class="login-container">
        <h2>登录</h2>
        <form method="post">
            <input type="password" name="password" placeholder="密码" required>
            <button type="submit">登录</button>
        </form>
    </div>

    <footer>
        <img src="footer.png" alt="Footer Image" style="display: block; margin: 0 auto; max-width: 60%; max-height: 125px;"/>
        <div class="footer-text">
            Made with ❤️ by dev group:
            <br>
            <a href="https://space.bilibili.com/562001644?spm_id_from=..0.0">Steven_Lee_147</a>, 
            <a href="https://space.bilibili.com/1718299194?spm_id_from=..0.0">CharlesZiy</a>, 
            Fitten Code, ChatGPT, and Github Copilot.
            <br>
            友链：
            <a href="https://space.bilibili.com/693772585?spm_id_from=..0.0">某知名英语老师</a> |
            <a href="https://memoir.rdfz.app/">黄庄回响集</a>

        </div>
    </footer>
</body>
</html>
    '''
@app.route('/list-images2')
def list_images2():
    # List all files in the upload directory with modification time
    images_with_mtime = [(f, os.path.getmtime(os.path.join('15', f))) for f in os.listdir('15') if os.path.isfile(os.path.join('15', f))]
    
    # Sort images based on modification time
    sorted_images = sorted(images_with_mtime, key=lambda x: x[1], reverse=True)
    
    # Extract file names from sorted list
    sorted_image_names = [img[0] for img in sorted_images]
    
    return jsonify(sorted_image_names)

@app.route('/list-images')
def list_images():
    # List all files in the upload directory with modification time
    images_with_mtime = [(f, os.path.getmtime(os.path.join(UPLOAD_FOLDER, f))) for f in os.listdir(UPLOAD_FOLDER) if os.path.isfile(os.path.join(UPLOAD_FOLDER, f))]
    
    # Sort images based on modification time
    sorted_images = sorted(images_with_mtime, key=lambda x: x[1], reverse=True)
    
    # Extract file names from sorted list
    sorted_image_names = [img[0] for img in sorted_images]
    
    return jsonify(sorted_image_names)



@app.route('/upload', methods=['POST'])
def upload():
    if 'file' not in request.files:
        return jsonify({'message': 'No file part'}), 400

    files = request.files.getlist('file')  # 获取上传的文件列表
    
    uploaded_files = []
    for file in files:
        if file.filename == '':
            return jsonify({'message': 'No selected file'}), 400

        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            filepath = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
            unzipped_filepath = os.path.join(app.config['UNZIPPED_FOLDER'], filename)
            file.seek(0) 
            file.save(filepath)
            # 重置文件指针
            file.save(unzipped_filepath)  # 保存到未压缩文件夹

            # 获取文件的 MIME 类型，判断是图片还是视频
            mime_type = file.content_type

            #if mime_type.startswith('image/'):
            #    # 如果是图片，则进行压缩处理
            #    try_count = 0
            #    while os.path.getsize(filepath) > 1000 * 1024 and try_count < 2:
            #        try:
            #            img = Image.open(filepath)
            #            img.save(filepath, optimize=True, quality=70)  # 使用70%的质量压缩图片
            #            try_count += 1
            #        except Exception as e:
            #            return jsonify({'message': f'Error occurred while compressing image: {str(e)}'}), 500
#
            #    # 如果压缩后图片仍大于500KB，继续压缩
           #     try_count = 0
            #    while os.path.getsize(filepath) > 500 * 1024 and try_count < 2:
            #        try:
            #            img = Image.open(filepath)
            #            img.save(filepath, optimize=True, quality=50)  # 使用50%的质量再次压缩
            #            try_count += 1
            #        except Exception as e:
             #           return jsonify({'message': f'Error occurred while compressing image: {str(e)}'}), 500

            #elif mime_type.startswith('video/'):
                # 如果是视频，则进行视频压缩处理
            #    try:
            #        video = mp.VideoFileClip(filepath)
            #        compressed_video_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            #        video.write_videofile(compressed_video_path, codec="libx264", bitrate="1200k")  # 以较低比特率压缩视频
            #    except Exception as e:
            #       return jsonify({'message': f'Error occurred while compressing video: {str(e)}'}), 500

            # 创建图片名称的文件夹并添加空的comments.txt
            image_folder = os.path.join(app.config['UPLOAD_FOLDER'], os.path.splitext(filename)[0])
            os.makedirs(image_folder, exist_ok=True)
            comments_file = os.path.join(image_folder, 'comments.txt')
            with open(comments_file, 'w') as f:
                pass  # 创建一个空的 comments 文件

            uploaded_files.append(filename)
        else:
            return jsonify({'message': 'Invalid file format or extension'}), 400

    print(datetime.datetime.now(),'--Files uploaded successfully')

    return jsonify({'message': 'Files uploaded successfully', 'files': uploaded_files}), 200

@app.route('/upload-comment', methods=['POST'])
def upload_comment():
    data = request.json
    filename = data.get('filename')
    comment = data.get('comment')
    
    if filename is None or comment is None:
        print(datetime.datetime.now(),'--Invalid data')
        return jsonify({'success': False, 'message': 'Invalid data'}), 400
    
    # 获取用户IP地址
    user_ip = request.remote_addr
    # 获取当前时间
    timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    # 构造保存路径
    folder_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
    if not os.path.exists(folder_path):
        os.makedirs(folder_path)
    
    # 构造 JSON 数据结构
    comment_data = {
        "comment": comment,
        "timestamp": timestamp,
        "ip": user_ip
    }

    # 将评论保存为 JSON 格式
    comment_filepath = os.path.join(folder_path, 'comments.json')
    
    if os.path.exists(comment_filepath):
        # 如果文件存在，则读取并追加
        with open(comment_filepath, 'r') as f:
            try:
                comments_list = json.load(f)
            except json.JSONDecodeError:
                comments_list = []
    else:
        # 如果文件不存在，创建一个新的列表
        comments_list = []
    
    comments_list.append(comment_data)
    
    # 写入文件
    with open(comment_filepath, 'w') as f:
        json.dump(comments_list, f, indent=4)
    
    print(datetime.datetime.now(), '--Comment uploaded successfully')
    return jsonify({'success': True}), 200

@app.route('/get-comments/<filename>')
def get_comments(filename):
    folder_path = os.path.join(app.config['UPLOAD_FOLDER'], os.path.splitext(filename)[0])
    comment_filepath = os.path.join(folder_path, 'comments.json')
    
    if os.path.exists(comment_filepath):
        with open(comment_filepath, 'r') as f:
            try:
                comments = json.load(f)
                # Extract all comment texts and replace newlines with <br>
                if comments:
                    comment_texts = '<br>'.join([comment['comment'] for comment in comments])
                else:
                    comment_texts = ''  # Return empty if there are no comments
            except json.JSONDecodeError:
                comment_texts = ''
        return comment_texts  # Return comment text with <br> tags for line breaks
    else:
        return ''  # Return empty if the file doesn't exist

@app.route('/spring-countdown-data')
def spring_countdown_data():
    # 获取当前日期
    today = datetime.datetime.now()
    start_date = datetime.datetime(2025, 1, 19)
    delta_days = (today - start_date).days

    # 获取 winter 文件夹中的所有图片文件
    winter_folder = 'winter'
    image_files = [f for f in os.listdir(winter_folder) if os.path.isfile(os.path.join(winter_folder, f))]

    # 按文件修改时间排序
    image_files.sort(key=lambda x: os.path.getmtime(os.path.join(winter_folder, x)))

    # 计算当前序号的图片
    current_image = image_files[delta_days % len(image_files)]

    # 计算数九进度
    winter_solstice = datetime.datetime(today.year, 12, 21)
    days_since_solstice = (today - winter_solstice).days
    current_nine = days_since_solstice // 9 + 1
    days_in_current_nine = days_since_solstice % 9 + 1

    # 修正数九进度
    if days_since_solstice < 0:
        winter_solstice = datetime.datetime(today.year - 1, 12, 21)
        days_since_solstice = (today - winter_solstice).days
        current_nine = days_since_solstice // 9 + 1
        days_in_current_nine = days_since_solstice % 9 + 1

    # 将 current_nine 转换为大写汉字
    chinese_numerals = ["一", "二", "三", "四", "五", "六", "七", "八", "九"]
    current_nine_chinese = chinese_numerals[current_nine - 1]

    # 计算农历日期
    lunar_date = lunarcalendar.Lunar.from_date(today)
    lunar_month = lunar_date.month

    if lunar_month == 12:
        lunar_month = "腊"
    elif lunar_month == 1:
        lunar_month = "正"
    elif lunar_month == 2:
        lunar_month = "二"
    elif lunar_month == 3:
        lunar_month = "三"
    elif lunar_month == 4:
        lunar_month = "四"
    elif lunar_month == 5:
        lunar_month = "五"
    elif lunar_month == 6:
        lunar_month = "六"
    elif lunar_month == 7:
        lunar_month = "七"
    elif lunar_month == 8:
        lunar_month = "八"
    elif lunar_month == 9:
        lunar_month = "九"
    elif lunar_month == 10:
        lunar_month = "十"
    elif lunar_month == 11:
        lunar_month = "冬"

    if lunar_date.day < 10:
        lunar_day = "初" + chinese_numerals[lunar_date.day-1]
    elif lunar_date.day == 10:
        lunar_day = "初十"
    elif lunar_date.day < 20:
        lunar_day = "十" + chinese_numerals[lunar_date.day - 10-1]
    elif lunar_date.day ==20:
        lunar_day = "二十"
    elif lunar_date.day < 30:
        lunar_day = "廿" + chinese_numerals[lunar_date.day - 20-1]
    else:
        lunar_day = "卅"
    
    # 天干地支纪年法
    tian_gan = ["甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"]
    di_zhi = ["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"]
    year = today.year
    tian_gan_index = (year - 4) % 10
    di_zhi_index = (year - 4) % 12

    # 修正天干地支纪年法
    if today.month < 2 or (today.month == 2 and today.day < 4):
        tian_gan_index = (year - 5) % 10
        di_zhi_index = (year - 5) % 12

    lunar_year = f"{tian_gan[tian_gan_index]}{di_zhi[di_zhi_index]}"
    
    lunar_date_str = f"{lunar_year}年{lunar_month}月{lunar_day}日"

    data = {
        "image_url": f"/winter/{current_image}",
        "gregorian_date": today.strftime("%Y年%m月%d日"),
        "lunar_date": lunar_date_str,
        "sijiu_progress": f"数九进度: 第{current_nine_chinese}九，第{days_in_current_nine}天"
    }
    return jsonify(data)

@app.route('/motto')
def get_motto():
    with open('mottos.json', 'r', encoding='utf-8') as f:
        mottos = json.load(f)
    random_motto = random.choice(mottos)
    return jsonify(random_motto)

if __name__ == '__main__':
    from waitress import serve
    serve(app, host='0.0.0.0', port=2319)
